import Cookies from 'js-cookie';
import config from '@/config'

const { cookieExpires } = config;
const TOKEN_KEY = "token"; //这个是cookie的key

export const setToken = token => {
  Cookies.set(TOKEN_KEY,token,{ expires:cookieExpires || 1 });
};

export const getToken = () => {
  let token = Cookies.get(TOKEN_KEY);

  if(token){
    token = "Bearer " + token;
    return token;
  }

  else return null;
};

/**
 * @description 绑定事件 on(element, event, handler)
 */
export const on = (function () {
    if (document.addEventListener) {
        return function (element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false)
            }
        }
    } else {
        return function (element, event, handler) {
            if (element && event && handler) {
                element.attachEvent('on' + event, handler)
            }
        }
    }
})();

/**
 * @description 解绑事件 off(element, event, handler)
 */
export const off = (function () {
    if (document.removeEventListener) {
        return function (element, event, handler) {
            if (element && event) {
                element.removeEventListener(event, handler, false)
            }
        }
    } else {
        return function (element, event, handler) {
            if (element && event) {
                element.detachEvent('on' + event, handler)
            }
        }
    }
})();